/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

import utils.NoWeatherException;
import boundaries.WeatherService;
import entities.Invitation;
import entities.OutdoorEvent;
import utils.Weather;
import entities.WeatherForecast;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Alberto, Alessandra
 */
@Stateless
public class WeatherManager {
    
    private static final Logger logger = Logger.getLogger(WeatherManager.class.getName());
    
    @PersistenceContext
    EntityManager em;
    
    @EJB
    WeatherService ws;
    
    public ArrayList<WeatherForecast> getBadWeather (ArrayList<Weather> badweather) {
        ArrayList<WeatherForecast> res = new ArrayList<>();
        for (int i=0; i<badweather.size(); i++) {
            res.add(em.createNamedQuery("findWeatherByName" , WeatherForecast.class)
                .setParameter("Wname", badweather.get(i))
                .getSingleResult());
        }
        return res;
    }
    
    public void retrieveWeatherForecast (OutdoorEvent event) {
        try {
            Weather weather = ws.getWeatherForecast(event.getPlace().getCity(), event.getDate());
            event.setWeatherforecast(em.createNamedQuery("findWeatherByName" , WeatherForecast.class)
                    .setParameter("Wname", weather)
                    .getSingleResult());
        } catch (NoWeatherException e) {
            logger.log(Level.INFO, e.getMessage());
            event.setWeatherforecast(null);
        }
    }
    
    public Date computeProposedDate (OutdoorEvent event) {
        try {
            ArrayList<Weather> badweather = new ArrayList<>();
            Iterator<WeatherForecast> iter = event.getBadweather().iterator();
            while (iter.hasNext()) {
                badweather.add(iter.next().getName());
            }
            return ws.getProposedDate(event.getPlace().getCity(), event.getDate(), badweather);
        } catch (NoWeatherException e) {
            return null;
        }
    } 
    
}
